package cn.ztydata.teachingsystem.heaven.web.controller;

import cn.ztydata.teachingsystem.common.Page;
import cn.ztydata.teachingsystem.exception.ServiceException;
import cn.ztydata.teachingsystem.heaven.cons.Roles;
import cn.ztydata.teachingsystem.heaven.entity.Department;
import cn.ztydata.teachingsystem.heaven.entity.Role;
import cn.ztydata.teachingsystem.heaven.entity.User;
import cn.ztydata.teachingsystem.heaven.service.AuthorizeService;
import cn.ztydata.teachingsystem.heaven.service.DepartmentService;
import cn.ztydata.teachingsystem.heaven.service.SpecialtyService;
import cn.ztydata.teachingsystem.heaven.service.TeacherService;
import cn.ztydata.teachingsystem.heaven.web.dto.DepartmentDto;
import cn.ztydata.teachingsystem.heaven.web.dto.DeptStatisticsDto;
import cn.ztydata.teachingsystem.heaven.web.wrapper.HttpSessionProxy;
import cn.ztydata.teachingsystem.webservice.result.json.JsonResult;
import cn.ztydata.teachingsystem.webservice.result.json.JsonResultData;
import cn.ztydata.teachingsystem.webservice.result.json.JsonResultList;
import cn.ztydata.teachingsystem.webservice.result.json.JsonResultPage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 系部控制器类
 *
 * @author fanruiping
 * @since 2014-11-29
 */
@Controller
@RequestMapping("/depart")
public class DepartmentController extends BaseController {
    @Autowired
    private DepartmentService departmentService;
    @Autowired
    private AuthorizeService authorizeService;
    @Autowired
    private SpecialtyService specialtyService;
    @Autowired
    private TeacherService teacherService;
    @Value("${session.key}")
    private String sessionKey;
    /**
     * 系部列表
     * @param pageNum
     * @return JsonResultList
     *
     * @author fanruiping
     * @since 2014-11-29
     */
    @RequestMapping(value = "/list/{pageNum}", method = RequestMethod.GET)
    @ResponseBody
    public JsonResultList list(@PathVariable int pageNum){
        pageNum = pageNum < 1 ? 1 : pageNum;

        Page<Department> page = departmentService.getList(pageNum, 20);

        Page<DepartmentDto> dtoPage = new Page<>(page.getTotal(),page.getSize(),page.getNum(),mapper.mapList(page.getItems(), DepartmentDto.class));

        log.debug("return department list");

        return new JsonResultPage(dtoPage);
    }

    /**
     * 系部下拉列表
     * @param tag 标记（0：全部，1：按照用户角色获取）
     * @return JsonResult
     *
     * @author fanruiping
     * @since 2014-12-02
     */
    @RequestMapping(value = "/comboList", method = RequestMethod.GET)
    @ResponseBody
    public JsonResult comboList(@RequestParam(value = "tag", defaultValue = "0", required = false) int tag,HttpServletRequest request){

        User userInfo = (User)((HttpSessionProxy)request.getSession()).getAttribute(sessionKey);

        List<Department> entities = new ArrayList<>();

        //判断当前用户是院级用户、超级管理员或标记为0，获取所有系部
        if(userInfo.getRole() == Roles.COLLEGE_USER || userInfo.getRole() == Roles.SUPER_ADMIN || 0 == tag ){
            entities = departmentService.getAll();
        }else{
            log.debug("当前用户的角色是系部管理员:userInfo.getRole() == Roles.DEPT_ADMIN");

            //当前用户是系部负责人
            if(userInfo.getRole() == Roles.DEPT_ADMIN){
                entities = departmentService.getByLeader(userInfo.getUserId());
            }else if(userInfo.getRole() == Roles.SPEC_LEADER){//当前用户是专业负责人
                entities = departmentService.getBySpecLeader(userInfo.getUserId());
            }
        }

        log.debug("return department list");

        return new JsonResultList(mapper.mapList(entities, DepartmentDto.class));
    }

    /**
     * 新增系部
     * @param dto
     * @return JsonResult
     *
     * @author fanruiping
     * @since 2014-11-29
     */
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    @ResponseBody
    public JsonResult add(@Valid @RequestBody DepartmentDto dto){
        //判断系部编码是否已存在
        if(null != departmentService.getDetailByNumber(dto.getCode())){
            log.debug("department is exist:null != departmentService.getDetailByNumber(dto.getCode())");

            return new JsonResult(false, "系部编码为"+dto.getCode()+"的数据已存在");
        }

        Department entity = mapper.map(dto, Department.class);

        departmentService.add(entity);

        log.debug("return true");

        return new JsonResult(true,"系部数据添加成功");
    }

    /**
     * 更新系部数据
     * @param dto
     * @return
     */
    @RequestMapping(value = "/edit", method = RequestMethod.PUT)
    @ResponseBody
    public JsonResult edit(@Valid @RequestBody DepartmentDto dto){
        Department department = departmentService.getDetail(dto.getId());

        //判断系部存不存在
        if(department == null){
            log.debug("department is not exist");

            return new JsonResult(false, "系部数据不存在");
        }

        //判断系部编码是否已存在
        if(department.getNumber() != dto.getCode() && null != departmentService.getDetailByNumberAndId(dto.getCode(), dto.getId())){
            log.debug("根据新编码判断系部已存在:department.getNumber() != dto.getCode() && null != departmentService.getDetailByNumberAndId(dto.getCode(), dto.getId())");

            return new JsonResult(false, "系部编码为"+dto.getCode()+"的数据已存在");
        }

        Department entity = mapper.map(dto, Department.class);

        try {
            departmentService.modify(entity);

            log.debug("department update success:return true");

            return new JsonResult(true, "系部数据更新成功");
        }catch (ServiceException ex){
            log.debug("department update fail:return false");

            return new JsonResult(false, "系部数据更新失败");
        }
    }

    /**
     * 删除指定系部数据
     * @param id 编号
     * @return JsonResult
     *
     * @author fanruiping
     * @since 2014-11-29
     */
    @RequestMapping(value = "/delete/{id}", method = RequestMethod.DELETE)
    @ResponseBody
    public JsonResult delete(@PathVariable long id){
        Department entity = departmentService.getDetail(id);

        //判断数据是否存在
        if(null == entity){
            log.debug("department is not exist:null == entity");

            return new JsonResult(false, "系部数据不存在");
        }

        //判断系部下是否有专业或教师数据
        if(teacherService.checkHasTeacherByDeptNum(entity.getNumber()) || specialtyService.checkHasSpecialtyByDeptNum(entity.getNumber())){
            log.debug("系部下有专业或教师数据");

            return new JsonResult(false, "请先删除系部下的专业或教师数据，再执行删除");
        }

        if(1 > departmentService.delete(id)){
            log.debug("系部数据删除失败:1 > departmentService.delete(id)");

            return new JsonResult(false, "系部数据删除失败");
        }

        log.debug("系部数据删除成功:1 <= departmentService.delete(id)");

        return new JsonResult(true, "指定系部数据删除成功");
    }

    /**
     * 获取明细
     * @param id 编号
     * @return JsonResult
     *
     * @author fanruiping
     * @since 2014-12-01
     */
    @RequestMapping(value = "/detail/{id}", method = RequestMethod.GET)
    @ResponseBody
    public JsonResult detail(@PathVariable long id){
        Department entity = departmentService.getDetail(id);

        if (null == entity){
            log.debug("指定系部不存在:null == entity");

            return new JsonResultData(false, "查看的系部数据不存在");
        }

        log.debug("return department detail");

        return new JsonResultData<>(mapper.map(entity, DepartmentDto.class));
    }

    /**
     * 获取首页系部列表
     *
     * @author chenxin
     * @since 2015/1/10
     */
    @RequestMapping(value = "/indexList", method = RequestMethod.GET)
    @ResponseBody
    public JsonResultList<DeptStatisticsDto> getIndexList() {
        //获取首页系部列表信息
        List<Department> deptInfoList = departmentService.getIndexList(5);

        //映射到dto类
        log.debug("获取首页系部列表");
        return new JsonResultList<>(mapper.mapList(deptInfoList, DeptStatisticsDto.class));
    }
}